<template>
  <div>
    <el-card class="search-card">
      <basic-form
        ref="formData"
        formItemWidth="150px"
        showColon
        defaultExpandStatus
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="clearCategorySelect"
        @getFormData="getFormData"
      >
        <CategoryMultipleSelect
          slot="category"
          ref="categoryMultiple"
          @selectCategoryCallback="setFormCateUuids"
        />
      </basic-form>
    </el-card>
    <el-card class="table-card">
      <skus-table
        showSelectCol
        showPagination
        :tableHeight="480"
        :actionColWidth="200"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :selectionChange="TableInfo.setSelection"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </el-card>
    <NotDevDialog
      :visible.sync="notDev.visible"
      :confirm-method="dataNotDevelop"
    />
    <SelectDevTypeDialog
      :visible.sync="selectDevType.visible"
      @getDevType="updateDevType"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import NotDevDialog from './components/NotDevDialog';
import SelectDevTypeDialog from './components/SelectDevTypeDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { FORM_ITEMS, TABLE_COLUMNS, ANALYSIS_STATUS, LATENT_DEV_POOL_INFO_KEY } from './constants';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import {
  setAuthBtnId,
  isResponseSuccess,
  handleOpenNewPage,
  createExcelByExport,
  generateUuid
} from '@/utils/bizUtils';
import {
  getPagerService,
  notDevelopService,
  reviewPassService,
  reviewFailService,
  potentialAnalysisExportService
} from '@/api/commodity/temporaryPurchasingGoods/latentProductDataAnalysis';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    CategoryMultipleSelect,
    NotDevDialog,
    SelectDevTypeDialog
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      // 暂不开发
      notDev: {
        visible: false
      },
      // 选择开发类型
      selectDevType: {
        visible: false,
      },
      // 按钮loading
      btnLoading: {
        export: false,
      }
    }
  },
  created () {
    this.executeTodoParams()
    this.handleQueryForm()
  },
  computed: {
    // 勾选数据全部为待审核状态
    isAllToReview () {
      const state = this.TableInfo.selection.every(
        item => item.analysisStatus == ANALYSIS_STATUS.ToReview
      )
      return state
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const disabled = this.TableInfo.isNullSelection() // 按钮禁用属性
      const finalBtns = [
        { label: '查看订货明细', method: this.handleViewOrderDetails, disabled },
        {
          label: '加入开发需求池',
          method: this.handleAddDevReqPool,
          disabled,
          hasAuth: true,
          authLabel: '新增开发需求'
        },
        {
          label: '暂不开发',
          method: this.handleUndevelop,
          disabled,
          hasAuth: true,
        },
        {
          label: '审核通过',
          method: this.handleReviewPass,
          disabled,
          hasAuth: true,
          authLabel: '审核'
        },
        {
          label: '审核驳回',
          method: this.handleReviewReject,
          disabled,
          hasAuth: true,
          authLabel: '审核'
        },
        {
          label: '导出',
          method: this.handleExport,
          hasAuth: true,
          loading: this.btnLoading.export
        }
      ]
      return getListPageBtnsBar(h, finalBtns, this.showBtn, 'start')
    },
    // 处理代办参数
    executeTodoParams () {
      const { analysisStatus } = this.$route.query ?? {}
      if (!analysisStatus) return
      this.formData = { ...this.formData, analysisStatus }
    },
    // 查看订货明细
    handleViewOrderDetails () {
      const orderDetails = this.TableInfo.selection.map(item => _.pick(item, ['skuNo', 'areaId']))
      localStorage.setItem('product_record_skus', JSON.stringify(orderDetails))
      handleOpenNewPage(this, {
        name: 'bidRecord',
        query: { source: '1' }
      })
    },
    // 加入开发需求池
    handleAddDevReqPool () {
      const canAdd = this.TableInfo.selection.every(
        item => [ANALYSIS_STATUS.ToProcess, ANALYSIS_STATUS.NotDevelop].includes(item.analysisStatus)
      )
      if (!canAdd) return this.$message.warning('只有待处理和暂不开发状态可以加入开发需求池，请取消非不符合条件的勾选项')
      setAuthBtnId('新增开发需求')
      this.selectDevType.visible = true
    },
    // 暂不开发
    handleUndevelop () {
      const isAllToProcess = this.TableInfo.selection.every(
        item => item.analysisStatus == ANALYSIS_STATUS.ToProcess
      )
      if (!isAllToProcess) return this.$message.warning('只有待处理状态可以进行暂不开发，请取消非不符合条件的勾选项')
      setAuthBtnId('暂不开发')
      this.notDev.visible = true
    },
    // 审核通过
    handleReviewPass () {
      if (!this.isAllToReview) return this.$message.warning('只有待审核状态可以进行审核通过，请取消非不符合条件的勾选项')
      setAuthBtnId('审核')
      this.openReviewSucessMsgBox()
    },
    // 审核驳回
    handleReviewReject () {
      if (!this.isAllToReview) return this.$message.warning('只有待审核状态可以进行审核驳回，请取消非不符合条件的勾选项')
      setAuthBtnId('审核')
      this.openReviewRejectMsgBox()
    },
    // 导出
    async handleExport () {
      setAuthBtnId('查询')
      const data = { ...this.formData }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await potentialAnalysisExportService(data, loadingFn)
      createExcelByExport({ res, excelTitle: `潜在商品分析列表_${generateUuid()}` })
    },
    // 获取表格数据
    async getTableData () {
      setAuthBtnId('查询')
      const data = { ...this.formData, ...this.paginationParams }
      const res = await getPagerService(data, this.TableInfo.setLoading)
      this.TableInfo.setList(res?.retData?.results ?? [])
      this.setTotalNum(res?.retData?.totalNum ?? 0)
    },
    // 获取关联品类信息
    setFormCateUuids (list) {
      this.formData.categoryUuids = list.map(item => item.categoryUuid)
    },
    // 清空品类选择信息
    clearCategorySelect () {
      this.$refs.categoryMultiple.clearSelectResult()
    },
    // 打开审核通过弹框
    openReviewSucessMsgBox () {
      this.$confirm('确定审核通过吗？', '提示', {
        type: 'warning',
        beforeClose: async (action, instance, done) => {
          if (action !== 'confirm') return done()
          this.dataReviewPass(instance, done)
        },
      }).catch(() => {})
    },
    // 打开审核驳回弹框
    openReviewRejectMsgBox () {
      this.$confirm('请输入审核驳回原因', '提示', {
        showInput: true,
        beforeClose: async (action, instance, done) => {
          if (action !== 'confirm') return done()
          if (!instance?.inputValue) return this.$message.warning('审核驳回原因不能为空！')
          this.dataReviewReject(instance, done)
        },
      }).catch(() => {})
    },
    // 审核通过请求
    async dataReviewPass (instance, done) {
      const data = this.TableInfo.selection.map(item => item.uuid)
      const loadingFn = state => { instance.confirmButtonLoading = state }
      const res = await reviewPassService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('操作成功')
        done()
        this.getTableData()
      }
    },
    // 审核驳回请求
    async dataReviewReject (instance, done) {
      const data = {
        uuids: this.TableInfo.selection.map(item => item.uuid),
        reviewFailRemark: instance?.inputValue
      }
      const loadingFn = state => { instance.confirmButtonLoading = state }
      const res = await reviewFailService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('操作成功')
        done()
        this.getTableData()
      }
    },
    // 暂不开发请求
    async dataNotDevelop (notDevParams, loadingFn) {
      const data = {
        uuids: this.TableInfo.selection.map(item => item.uuid),
        ...notDevParams
      }
      const res = await notDevelopService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('操作成功')
        this.notDev.visible = false
        this.getTableData()
      }
    },
    // 加入开发需求池
    updateDevType (devType) {
      const uniqueKeys = this.TableInfo.selection.map(item => item.uniqueKey)
      localStorage.setItem(LATENT_DEV_POOL_INFO_KEY, JSON.stringify(uniqueKeys))
      this.$router.push({
        name: 'developRequirementPoolLatentAdd',
        query: { devType }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .table-action {
  margin-right: 0;
}
</style>
